package xorms

import (
	"context"
	"fmt"
	diaryModel "go-weixin/app/diary/model"
	guitarModel "go-weixin/app/guitar/model"
	musicModel "go-weixin/app/music/model"
	orderModel "go-weixin/app/order/model"
	userModel "go-weixin/app/usercenter/model"
	"go-weixin/common/chendb"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/core/logx"
	"xorm.io/xorm"
)

type XormsDb struct {
	engine  *chendb.ChenDb
	session *xorm.Session
}

// 配置数据库连接
func Dbconn(dns string, showsql bool, migrate bool, serviceName string) *chendb.ChenDb {
	engine, err := xorm.NewEngine("mysql", dns)
	engine.ShowSQL(showsql)
	engine.TZLocation, _ = time.LoadLocation("Asia/Shanghai")
	engine.SetMaxIdleConns(10) //空闲连接
	engine.SetMaxOpenConns(50) //最大连接
	if err != nil {
		logc.Error(context.Background(), "数据库连接失败")
	} else {
		logc.Info(context.Background(), "数据库连接成功")
	}

	// 配置模型迁移(根据不同的服务执行)
	if migrate {
		switch serviceName {
		case "user-rpc":
			logc.Info(context.Background(), "userrpc执行数据库迁移")
			engine.Sync(new(userModel.UserModel), new(userModel.RoleModel), new(userModel.PowerModel), new(userModel.UserRoleModel), new(userModel.RolePowerModel), new(userModel.TablesModel))
		case "music-rpc":
			logc.Info(context.Background(), "musicrpc执行数据库迁移")
			engine.Sync(new(musicModel.MusicModel))
		case "diary-rpc":
			logc.Info(context.Background(), "diary执行数据库迁移")
			engine.Sync(new(diaryModel.DiaryModel))
		case "order-api":
			logc.Info(context.Background(), "order.api执行数据库迁移")
			engine.Sync(new(orderModel.CommodityModel), new(orderModel.OrderModel), new(orderModel.OrderCommodityModel))
		case "guitar-rpc":
			logc.Info(context.Background(), "guitar.rpc执行数据库迁移")
			engine.Sync(new(guitarModel.GuitarModel), new(guitarModel.GuitarImageModel))
		}

	}
	return &chendb.ChenDb{Engine: engine}
}

func NewXormsDb(username string, password string, host string, port int, databases string, showsql bool, migrate bool, serviceName string) *chendb.ChenDb {
	dns := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, databases)
	return Dbconn(dns, showsql, migrate, serviceName)
}

// 没用
func (x *XormsDb) Session() {
	x.session = x.engine.NewSession()
	//记得关闭 defer x.session.Close()
}

// 没用
func (x *XormsDb) Begin() error {
	err := x.session.Begin()
	if err != nil {
		logx.Error(err)
		return err
	}
	return nil
}

// 没用
func (x *XormsDb) Rollback() error {
	err := x.session.Rollback()
	if err != nil {
		logx.Error(err)
		return err
	}
	return nil
}

// 没用
func (x *XormsDb) Commit() error {
	err := x.session.Commit()
	if err != nil {
		logx.Error(err)
		return err
	}
	return nil
}
